<?php

namespace App\Http\Middleware;

use App\Master\Enum\MenuEnum;
use App\Master\Framework\Extend\Core;
use App\Master\Framework\Extend\Module;
use App\Models\Admin\Framework\AdminMenusModel;
use Closure;
use Illuminate\Http\Request;

class AdminAgent
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if ($request->isMethod('get')) {
            $menus = $this->currentMenus($request->url(), $request->header('referer'));

            if (!$settings = Module::_SetupModule('SiteSettings')) {
                $settings = [
                    'login_bg'    => '',
                    'login_logo'  => '',
                    'login_title' => '鲸蓝管理系统',
                    'left_logo'   => '',
                    'left_title'  => '鲸蓝管理系统',
                    'favicon'     => isset($settings['favicon']) ? $settings['favicon'] : '/favicon.ico'
                ];
            }
            // 获取前端默认选中菜单标识 key
            $menuEnum = new MenuEnum();
            $currentItems = $menuEnum->getCurrentItems();
            $layoutsLeftMenuEvent = $menuEnum->getLayoutsLeftMenuEvent();
            $params = [
                'settings'      => $settings,
                'current_menus' => $menus,
                'currentItems' => md5($currentItems),
                'layoutsLeftMenuEvent' => md5($layoutsLeftMenuEvent),
            ];
            view()->share($params);
        }

        return $next($request);
    }

    protected function currentMenus($url, $referer)
    {
        $prefix = config('admin.prefix');

        $hosts = Core::HostDomain();

        $url = array_values(array_filter(explode($hosts, $url)));

        $referer = array_values(array_filter(explode($hosts, $referer)));

        // 获取前端默认选中菜单标识 key
        $menuEnum = new MenuEnum();
        $currentItems = $menuEnum->getCurrentItems();
        $layoutsLeftMenuEvent = $menuEnum->getLayoutsLeftMenuEvent();

        $select = ['id', 'icon', 'name', 'path', 'facility', 'parent_id'];
        $link = '';
        if (!empty($url[0])){
            $link = str_replace("/{$prefix}/",'', $url[0]);
        }elseif (!empty($referer[0])){
            $link = str_replace("/{$prefix}/",'', $referer[0]);
        }

        if (!empty($link)) {
            if ($current_items = AdminMenusModel::query()->select($select)->where('path', $link)->where('status', 1)->where('is_delete',0)->first()) {
                $current_items->menu_id = $current_items->facility == '2' ? $current_items->parent_id : $current_items->id;
                Core::setCookie($currentItems, $current_items);
                Core::setCookie($layoutsLeftMenuEvent, $current_items->menu_id);
                return $current_items;
            }
        }

        if ($menu_id = Core::getCookie($layoutsLeftMenuEvent)) {
            if ($current_items = AdminMenusModel::query()->select($select)->where('id', $menu_id)->where('status', 1)->where('is_delete',0)->first()) {
                $current_items->menu_id = $current_items->facility == '2' ? $current_items->parent_id : $current_items->id;
                Core::setCookie($currentItems, $current_items);
                Core::setCookie($layoutsLeftMenuEvent, $current_items->menu_id);
                return $current_items;
            }
        }

        Core::setCookie($currentItems, null, -1);
        Core::setCookie($layoutsLeftMenuEvent, null, -1);
        return [];
    }
}
